package com.fatsatsuma.spreadsheets;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import junit.framework.TestCase;

public class SpreadsheetRowListenerTestCase extends TestCase implements RowListener {

	private List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();

	private Logger log = Logger.getLogger(this.getClass());

	private String column1;
	private String column2;
	private Integer column3;
	private int currentRowNumber;

	public void setColumn1(String column1) {
		this.column1 = column1;
	}

	public void setColumn2(String column2) {
		this.column2 = column2;
	}

	public void setColumn3(Integer column3) {
		this.column3 = column3;
	}

	@Override
	public void setUp() {
		data.add(createRowMap("cell11", "cell12", new Integer(3)));
		data.add(createRowMap("cell21", "cell22", new Integer(6)));
		data.add(createRowMap("cell31", "cell32", new Integer(9)));
	}

	public Map<String, Object> createRowMap(Object value1, Object value2, Object value3) {
		Map<String, Object> row = new HashMap<String, Object>();
		row.put("column1", value1);
		row.put("column2", value2);
		row.put("column3", value3);
		return row;
	}

	public void execute() {
		log.info("Calling Execute...");
		assertEquals(data.get(currentRowNumber).get("column1"), column1);
		assertEquals(data.get(currentRowNumber).get("column2"), column2);
		assertEquals(data.get(currentRowNumber).get("column3"), column3);
		currentRowNumber++;
	}

	public void testRowListenerReading() throws Exception {
		log.info("Testing Valid File...");
		try {
			assertNotNull("Unable to load inputstream", getValid());
			SpreadsheetReader reader = new SpreadsheetReader(getValid());
			reader.registerRowListener(this);
			reader.readWorksheet("Sheet1");
			assertTrue(true);
		} catch (InvalidWorkbookException exp) {
			log.error("Unable to load spreadsheet", exp);
			assertTrue(false);
		} catch (Exception exp) {
			log.fatal("Fatal Error", exp);
			throw exp;
		}
	}

	private InputStream getValid() {
		return this.getClass().getClassLoader().getResourceAsStream(
				"spreadsheets/listener-spreadsheet.xls");
	}

}
